package com.example.teamtribe.main.mine.club;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.teamtribe.R;
import com.example.teamtribe.database.Team;
import com.example.teamtribe.main.club.clubdetail.ClubDetailActivity;
import com.example.teamtribe.utils.Utility;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class ClubGridAdapter extends RecyclerView.Adapter {

    private static final int TYPE_PAGER = 0;
    private static final int TYPE_ITEM = 1;
    private Context context;
    private List<Team> teams = new ArrayList<>();

    public void add(Team team) {
        teams.add(team);
        Collections.sort(teams);
    }

    public void addAll(Collection<Team> teams) {
        this.teams.addAll(teams);
        Collections.sort(this.teams);
    }

    public void clear() {
        teams.clear();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        context = parent.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.item_club, parent, false);
        final ItemViewHolder holder = new ItemViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition() - 1;
                Team team = teams.get(position);
                Intent intent = new Intent(context, ClubDetailActivity.class);
                intent.putExtra("team", team);
                context.startActivity(intent);
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ItemViewHolder) {
            ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
            Team team = teams.get(position);
            Glide.with(context).load(Utility.getUri(team.getPortrait())).into(itemViewHolder.ivPortrait);
            itemViewHolder.tvName.setText(team.getName());
        }
    }

    @Override
    public int getItemCount() {
        return teams.size();
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        ImageView ivPortrait;
        TextView tvName;

        public ItemViewHolder(View itemView) {
            super(itemView);
            ivPortrait = itemView.findViewById(R.id.iv_item_club);
            tvName = itemView.findViewById(R.id.tv_item_club);
        }
    }
}
